package wang.hex.codetransfer.code;


import wang.hex.codetransfer.code.gui.CodeImageGui;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.function.Function;

public class Sender {
    private CodeImageGui codeImageGui;
    private int len = 512;
    private int width;
    private int height;

    public Sender(int x, int y, int width, int height) {
        codeImageGui = CodeImageGui.of(x, y, width, height);
        this.width = width;
        this.height = height;
    }

    public Sender(int x, int y, int width, int height, int len) {
        this(x, y, width, height);
        this.len = len;
    }


    public void show(byte[] bytes) {
        codeImageGui.setImage(QRCoderGen.encode(bytes, width - 40, height - 40));
    }

    //前8位
    public void send(InputStream stream, Function<Long, Boolean> function) {
        byte[] bytes = new byte[len];
        long page = 0;
        int read = -1;
        try {
            while ((read = stream.read(bytes, 12, len - 12)) != -1) {
                BytesUtil.setLong2Bytes(page, bytes, 0);
                BytesUtil.setInt2Bytes(read, bytes, 8);
                show(bytes);
                if (function != null) {
                    Boolean apply = function.apply(page);
                    if (apply != true) {
                        break;
                    }
                }
                page++;
            }
            BytesUtil.setLong2Bytes(page, bytes, 0);
            BytesUtil.setInt2Bytes(read, bytes, 8);
            show(bytes);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void send(String path, long delay) {
        while (true) {
            try {
                send(new FileInputStream(path), (d) -> {
                    try {
                        Thread.sleep(delay);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return true;
                });
            } catch (Exception e) {

            }
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}
